<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar
      title="欢迎下单"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
      fixed
      placeholder
      z-index="999"
    >
      <template #right>
        <van-icon name="phone-o" size="24" />
      </template>
    </van-nav-bar>

    <!-- 滚动导航栏 -->
    <div class="tabs_wrap">
      <van-tabs
        v-model="active"
        scrollspy
        sticky
        offset-top="46"
        color="#1989fa"
      >
        <van-tab v-for="v in goodsList" :title="v.menuName" :key="v.menuID">
          <div>
            <van-card
              :tag="m.foodSales > 10 ? '火热' : '推荐'"
              :num="m.num"
              :price="m.foodPrice.toFixed(2)"
              :title="m.foodName"
              :thumb="m.foodImage"
              :origin-price="(m.foodPrice * 1.2).toFixed(2)"
              v-for="m in v.children"
              :key="m.foodID"
            >
              <template #desc>
                <div class="food_desc">{{ m.foodText }}</div>
              </template>
              <template #num>
                <span>{{ m.num == 0 ? "" : "x" + m.num }}</span>
              </template>
              <template #tags>
                <div class="food_surplus">{{ "剩余" + m.foodNum + "件" }}</div>
              </template>
              <template #footer>
                <!-- +-计算 -->
                <div
                  class="btn_add"
                  @click="showStepper(m)"
                  v-show="!m.stepperVisible"
                >
                  <van-icon name="plus" />
                </div>

                <van-stepper
                  v-model="m.num"
                  v-show="m.stepperVisible"
                  min="0"
                  @minus="subStepper(m)"
                  @plus="addStepper(m)"
                  disable-input
                />
              </template>
            </van-card>
          </div>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 底部结算栏 -->
    <van-submit-bar
      :price="totalPrice * 100"
      button-text="提交订单"
      button-type="info"
      safe-area-inset-bottom
      @submit="onSubmitOrder"
    >
      <van-icon name="shopping-cart-o" size="30" @click="showCart" />
    </van-submit-bar>

    <!-- 购物车详情 -->
    <van-action-sheet v-model="cartVisible" title="购物车">
      <div class="content">
        <van-cell-group>
          <van-cell
            :title="v.foodName"
            :value="'￥' + v.foodPrice"
            :label="'x' + v.num"
            v-for="v in cart"
            :key="v.foodID"
          />
        </van-cell-group>
        <van-cell title="合计" :value="'￥' + totalPrice" />
      </div>
    </van-action-sheet>

    <!-- 弹出选择支付方式 -->
    <van-popup
      v-model="showPayMethod"
      :style="{ height: '40%', width: '90%' }"
      round
      @close="closePay"
    >
      <div class="pay_container">
        <van-radio-group v-model="payMethodKey" @change="choosePayMethod">
          <van-radio name="0"
            ><van-image
              width="120"
              height="80"
              src="https://s1.ax1x.com/2020/05/25/t97U3D.png"
          /></van-radio>
          <van-radio name="1" disabled
            ><van-image
              width="120"
              height="80"
              src="http://img0.imgtn.bdimg.com/it/u=2108750751,269253045&fm=26&gp=0.jpg"
          /></van-radio>
          <van-radio name="2" disabled
            ><van-image
              width="120"
              height="80"
              src="http://l.b2b168.com/2016/04/03/10/201604031047520138184.jpg"
          /></van-radio>
          
        </van-radio-group>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { Dialog, Toast } from "vant";
export default {
  data() {
    return {
      active: 0,
      //购物车显示
      cartVisible: false,
      goodsList: [],
      //总价
      totalPrice: 0,
      cart: [],
      showPayMethod: false,
      payMethodKey: ""
    };
  },
  created() {
    this.getPageData();
  },
  methods: {
    //获取页面数据
    async getPageData() {
      let catesList, goodsList;
      //获取分类列表
      const { data: res0 } = await this.$http.get("menu");
      catesList = res0.data;
      //获取菜品列表
      const { data: res1 } = await this.$http.get("food");
      console.log("res1: ", res1);
      goodsList = res1.data;
      goodsList.forEach(v => {
        if (v.foodImage == "") {
          v.foodImage =
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2774391408,3578926483&fm=26&gp=0.jpg";
        }
      });
      //合并数据形成children
      catesList.map(v => {
        v.children = goodsList.filter(m => {
          return m.menuID == v.menuID;
        });
      });

      this.goodsList = catesList;

      // 加载本地购物车
      let cart = JSON.parse(window.localStorage.getItem("cart")) || [];
      this.computeTotal(cart);
      // 如果购物车为空,正常
      if (cart.length == 0) {
        goodsList.forEach(v => {
          v.stepperVisible = false;
          v.num = 0;
        });
      } else {
        // 如果购物车有商品，赋值num 和显示数目
        cart.forEach(v => {
          const index = goodsList.findIndex(m => m.foodID == v.foodID);
          goodsList[index].stepperVisible = v.stepperVisible;
          goodsList[index].num = v.num;
        });
      }
    },
    //点击左上角返回键
    onClickLeft() {
      this.$router.go(-1);
    },
    //点击右上角联系客服
    onClickRight() {
      Dialog.confirm({
        title: "联系客服",
        message: "您确定要拨打客服热线158****9548吗？"
      })
        .then(() => {})
        .catch(() => {});
    },
    // 点击提交订单
    onSubmitOrder() {
      //查找购物车
      let cart = JSON.parse(window.localStorage.getItem("cart")) || [];
      if (cart.length == 0) return Toast("请先添加食物哦！");
      Dialog.alert({
        message: "微信和支付宝功能努力开发中，敬请期待"
      }).then(() => {
        // on close
        //去选择支付方式
      this.showPayMethod = !this.showPayMethod;
      });
      
    },
    //点击底部购物车按钮
    showCart() {
      this.cartVisible = !this.cartVisible;
      //加载购物车所有信息
      const cart = JSON.parse(window.localStorage.getItem("cart"));
      this.cart = cart;
    },
    // 点击+号显示计数器
    showStepper(food) {
      food.num = 1;
      food.stepperVisible = !food.stepperVisible;
      let { foodName, foodPrice, foodID, num, stepperVisible } = food;
      //查找购物车
      let cart = JSON.parse(window.localStorage.getItem("cart")) || [];
      cart.push({
        foodName,
        foodPrice,
        foodID,
        num,
        stepperVisible
      });
      //保存到本地
      window.localStorage.setItem("cart", JSON.stringify(cart));
      this.computeTotal(cart);
    },
    //点击计数器的减号的时候
    subStepper(food) {
      let { foodName, foodPrice, foodID, num } = food;
      let cart = JSON.parse(window.localStorage.getItem("cart"));
      let index = cart.findIndex(v => v.foodID == foodID);
      // 判断是否值为1，如果为1需要隐藏，需要从购物车中去除这个商品
      if (food.num == 1) {
        food.stepperVisible = !food.stepperVisible;
        food.num = 0;
        cart.splice(index, 1);
      } else {
        // 如果不为1，减1
        food.num--;
        cart[index].num--;
      }
      //保存到本地
      window.localStorage.setItem("cart", JSON.stringify(cart));
      this.computeTotal(cart);
    },
    //点击计数器的加号的时候
    addStepper(food) {
      food.num++;
      let { foodName, foodPrice, foodID, num } = food;
      //查找购物车
      let cart = JSON.parse(window.localStorage.getItem("cart"));
      let index = cart.findIndex(v => v.foodID == foodID);
      cart[index].num++;
      //保存到本地
      window.localStorage.setItem("cart", JSON.stringify(cart));
      this.computeTotal(cart);
    },
    //封装计算总价
    computeTotal(cart) {
      var total = 0;
      cart.forEach(v => {
        console.log(total);
        total += v.foodPrice * v.num;
      });
      this.totalPrice = total;
    },
    //关闭弹出支付方式窗口
    closePay() {
      this.payMethodKey = "";
    },
    //点击了支付方式时触发
    async choosePayMethod() {
      let user = JSON.parse(window.localStorage.getItem("user"));
      //查找购物车
      let cart = JSON.parse(window.localStorage.getItem("cart"));
      let orderFood = [];
      cart.forEach(v => {
        orderFood.push({
          name: v.foodName,
          count: v.num,
          price: v.foodPrice,
          id: v.foodID
        });
      });
      let orderInfo = {
        userID: user.userID,
        orderUserName: user.userName,
        orderTrainName: user.address.trainName,
        orderTrainNum: user.address.trainNum,
        orderTrainSeat: user.address.seatNum,
        orderState: 0,
        orderDate: new Date().valueOf(),
        orderMoney: this.totalPrice,
        paymentMethod: this.payMethodKey,
        orderFood,
        userPhone: user.userPhone
      };
      console.log(orderInfo);

      //发送请求
      const { data: res } = await this.$http.post("orderfood", orderInfo);
      Toast.success("下单成功啦！");
      // 隐藏支付方式弹出层
      this.showPayMethod = !this.showPayMethod;
      //清除本地购物车
      window.localStorage.removeItem("cart");
      //重新加载页面数据
      this.getPageData();
    }
  }
};
</script>
<style lang="less" scoped>
.tabs_wrap {
  padding: 0 0 60px;
  .van-tabs {
    .van-tab {
    }
  }
}
.van-card {
  margin-bottom: 10px;
}
.btn_add {
  .van-icon {
    height: 28px;
    width: 28px;
    outline: 0;
    border: 0;
    border-radius: 3px;
    background-color: #f2f3f5;
    text-align: center;
    line-height: 28px;
    font-size: 16px;
    font-weight: lighter;
  }
}
.van-submit-bar {
  .van-icon {
    margin-left: 15px;
  }
}
.food_surplus {
  font-size: 10px;
  color: #666;
  margin-top: 10px;
}
.food_desc {
  margin-top: 5px;
  font-size: 10px;
}
.pay_container {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
